package com.campus.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

@Configuration
public class DruidConfig {
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }
    @Bean
    public ServletRegistrationBean StatViewServlet() {
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("loginUsername", "yhll");
        stringStringHashMap.put("loginPassword", "qiyana");

        stringStringHashMap.put("allow", "");//允许谁能访问
        stringStringHashMap.put("ss", "192.168.11.123"); //禁止谁访问
        bean.setInitParameters(stringStringHashMap); //设置初始化参数
        return bean;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filter = new FilterRegistrationBean();

        filter.setFilter(new WebStatFilter());
        Map<String, String> initParameters = new Hashtable<>();
        /**
         * 可选参数
         * exclusions 排除经常需要排除一些不必要的url，比如*.js,/jslib/*等
         * sessionStatMaxCount 缺省sessionStatMaxCount是1000个
         * sessionStatEnable   你可以关闭session统计功能
         * principalSessionName，使得druid能够知道当前的session的用户是谁。
         * principalCookieName  如果你的user信息保存在cookie中，你可以配置principalCookieName，使得druid知道当前的user是谁
         * profileEnable  druid 0.2.7版本开始支持profile，配置profileEnable能够监控单个url调用的sql列表。
         */
        initParameters.put("exclusions", "*.js,*.css,/druid/**"); //exclusions 过滤请求
        filter.setInitParameters(initParameters);
        return filter;
    }
}
